# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import frappe
from frappe import _

def get_data(data):
    """返回列表视图配置"""
    return [
        {
            "label": _("查看余料"),
            "icon": "fa fa-eye",
            "action": "open_scrap_material",
            "condition": "doc.scrap_material"
        },
        {
            "label": _("查看参考文档"),
            "icon": "fa fa-file-text",
            "action": "open_reference_document",
            "condition": "doc.reference_document"
        },
        {
            "label": _("查看事务历史"),
            "icon": "fa fa-history",
            "action": "view_transaction_history",
            "condition": "doc.scrap_material"
        }
    ]

def open_scrap_material(doc):
    """打开余料详情页"""
    frappe.open_in_new_tab = True
    window.open(f"/app/scrap-material/{doc.scrap_material}")

def open_reference_document(doc):
    """打开参考文档"""
    frappe.open_in_new_tab = True
    window.open(f"/app/{doc.reference_doctype.lower().replace(/\s+/g, '-')}/{doc.reference_name}")

def view_transaction_history(doc):
    """查看事务历史"""
    frappe.call({
        'method': 'scrap_management.scrap_management.doctype.scrap_transaction.scrap_transaction.ScrapTransaction.get_transaction_history',
        'args': {
            'scrap_material': doc.scrap_material,
            'limit': 50
        },
        'callback': function(r) {
            if (r.message && r.message.length > 0) {
                // 显示事务历史对话框
                let dialog = new frappe.ui.Dialog({
                    'title': __('余料事务历史'),
                    'fields': [
                        {
                            'fieldtype': 'HTML',
                            'fieldname': 'transaction_history'
                        }
                    ],
                    'primary_action': function() {
                        dialog.hide();
                    },
                    'primary_action_label': __('关闭')
                });
                
                // 构建事务历史表格
                let html = `
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>${__('事务类型')}</th>
                                <th>${__('日期')}</th>
                                <th>${__('时间')}</th>
                                <th>${__('数量变化')}</th>
                                <th>${__('变化前数量')}</th>
                                <th>${__('变化后数量')}</th>
                                <th>${__('参考文档')}</th>
                                <th>${__('创建者')}</th>
                                <th>${__('备注')}</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                r.message.forEach(function(transaction) {
                    html += `
                        <tr>
                            <td>${transaction.transaction_type}</td>
                            <td>${transaction.transaction_date}</td>
                            <td>${transaction.transaction_time}</td>
                            <td style="color: ${transaction.quantity_change > 0 ? 'green' : 'red'}">
                                ${transaction.quantity_change > 0 ? '+' : ''}${transaction.quantity_change}
                            </td>
                            <td>${transaction.old_quantity}</td>
                            <td>${transaction.new_quantity}</td>
                            <td>${transaction.reference_doctype ? transaction.reference_doctype + ': ' + transaction.reference_name : ''}</td>
                            <td>${transaction.created_by}</td>
                            <td>${transaction.remarks || ''}</td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                dialog.fields_dict.transaction_history.$wrapper.html(html);
                dialog.show();
            } else {
                frappe.msgprint(__('没有找到相关的事务历史记录'));
            }
        }
    })